<?php

namespace app\models;

use app\libs\XCaptcha;
use app\services\AdminService;

/**
 * Class Admin
 *
 */


class Admin extends BaseModel
{

    //登录表单传入字段
    public $username;
    public $passWord;
    public $verifyCode;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return "{{%admin}}";
    }
    /**
     * @inheritdoc
     * 场景
     */
    public function scenarios()
    {
        return [
            'login' => ['username', 'passWord', 'verifyCode'],
            'update' => ['userName','email','password','realName','groupId','statusIs','isLock','updateTime'],
        ];
    }
    /**
     * 验证规则
     * @return array
     */
    public function rules()
    {
        return [
            //用户名、密码、验证码必填
            [['userName','email','password','realName','groupId','statusIs','isLock','updateTime'], 'safe'],
            ['username', 'required', 'message' => '用户名不能为空','on' => 'login'],
            ['passWord', 'required', 'message' => '密码不能为空','on' => 'login'],
            ['verifyCode', 'required', 'message' => '验证码不能为空','on' => 'login'],
            ['verifyCode', 'validateCaptcha','on' => 'login'],
            ['passWord', 'validatePassword','on' => 'login'],
            ['username', 'validateUser','on' => 'login']
        ];
    }

    /**
     * 字段标签名
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'username'   => '',
            'passWord'   => '',
            'verifyCode' => '',
        ];
    }

    /**
     * 验证用户是否是后台登录用户
     */
    public function validatePassword($attribute, $params)
    {
        $AdminService = new AdminService();
        $adminModel   = new Admin();

        $check        = $AdminService->isAdminValid($this->username, $this->passWord);
        if (isset($check['isAdmin']) && $check['isAdmin'] == false) {
            $adminService = new AdminService();
            $user = $adminModel::find()
                                ->asArray()
                                ->where(['userName' => $this->username])
                                ->one();

            $setUserId    = $user['id'] ? $user['id'] : 0;
            $adminService->insertTraceLog('登录失败，密码不正确', $setUserId, $this->username, 'login_pass_error');
            if (!empty($user)) {
                $count = $adminService->getTodayLoginErrorCountByUserId($user['id']);
                if ($count > 10) {
                    $adminModel->dbUpdate('', ['isLock' => '1'], ['where' => "id={$user['id']}"]);
                }
            }
            $this->addError('passWord', '用户名或密码错误');
        }
        if (isset($check['isAdmin']) && $check['isAdmin'] == true && $check['info']['groupId'] == 2) {
            $this->addError('passWord', '用户已经被锁定，请联系管理！');
        }
    }

    /**
     * 验证用户是否存在
     */
    public function validateUser($attribute, $params)
    {
        $AdminService = new AdminService();
        $user         = $AdminService->isAdminUser($this->username);
        if (!$user) {
            $adminService = new AdminService();
            $adminService->insertTraceLog('登录失败，用户不存在', 0, $this->username, 'login_pass_error');
            $this->addError('username', '用户不存在');
        }
        if (isset($user['statusIs']) && $user['statusIs'] == 0) {
            $this->addError('username', '该用户未激活，请联系管理！');
        }
    }

    /**
     * 验证验证码是否正确
     */
    public function validateCaptcha($attribute, $params)
    {
        $xCaptcha = new XCaptcha();
        $res      = $xCaptcha->checkCode($this->verifyCode);
        if (!$res) {
            $this->addError('verifyCode', '验证码错误');
        }
    }
}
